package com.itxg.booksmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itxg.booksmanage.common.R;
import com.itxg.booksmanage.entity.Book;
import com.itxg.booksmanage.entity.dto.BookPage;
import com.itxg.booksmanage.entity.dto.PageDto;
import com.itxg.booksmanage.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    /**
     * tick
     *
     * @param json {"book":{"bookName":123},"bookPage":{"page":111}}
     */
    @PostMapping("/page")
    public R selectPage(@RequestBody String json) {
        // 1. JSON 对象转换，将前端传递参数映射为两个对象
        JSONObject jsonObject = JSON.parseObject(json);
        Book book = jsonObject.getObject("book", Book.class);
        BookPage bookPage = jsonObject.getObject("bookPage", BookPage.class);
        System.out.println(book);
        System.out.println(bookPage);
        // 2. 执行分页条件模糊查询业务
        IPage<Book> iPage = bookService.getPageByCons(bookPage, book);
        // 3. 现在的页数也是从 0 开始，所以加 1
        PageDto pageDto = new PageDto(iPage.getTotal(), iPage.getCurrent() + 1, iPage.getRecords());
        System.out.println(pageDto);
        return R.success(pageDto);
    }

    // tick
    @PutMapping("/update")
    public R update(@RequestBody Book book) {
        System.out.println(book);
        System.out.println("----------");
        if (bookService.updateBookById(book) > 0) {
            return R.success(1);
        }
        return R.error("更新失败");
    }

    // tick
    @DeleteMapping("/delete")
    public R deleteByIds(@RequestBody List<Integer> ids) {
        int i = bookService.deleteBookById(ids);
        return i > 0 ? R.success(i) : R.error("删除失败");
    }

    // tick
    @GetMapping("/get")
    public R get(@RequestParam("id") Integer id) {
        return R.success(bookService.selectById(id));
    }

    @PostMapping("/add")
    public R add(@RequestBody Book book) {
        return R.success(bookService.addBook(book));
    }

    // tick
    @GetMapping("/all")
    public R getAll() {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.last("limit 100");
        return R.success(bookService.list());
    }

}
